package com.wang.bootbuilder.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wang.bootbuilder.entity.param.RoleParam;
import com.wang.bootbuilder.entity.pojo.Role;
import com.wang.bootbuilder.entity.pojo.Menu;
import com.wang.bootbuilder.entity.pojo.User;
import com.wang.bootbuilder.entity.result.GetRolesResult;
import com.wang.bootbuilder.mapper.MenuMapper;
import com.wang.bootbuilder.mapper.RoleMapper;
import com.wang.bootbuilder.mapper.UserMapper;
import com.wang.bootbuilder.tools.JsonResult;
import com.wang.bootbuilder.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    UserMapper userMapper;

    /*
    添加角色
     */
    public JsonResult addRole(String roleName) {
        // 检索表中是否已经存在该角色
        HashMap<String, Object> selectMap = new HashMap<>();
        selectMap.put("role_name", roleName);
        List<Role> roleList = roleMapper.selectByMap(selectMap);
        if (!CollectionUtils.isEmpty(roleList)) {
            return JsonResult.error().message("该角色已经存在，请重新添加");
        }
        // 插入该角色
        Role insertRole = new Role();
        insertRole.setRoleName(roleName);
        // 默认为所有角色都设置首页权限
        insertRole.setMenuIds("1");
        roleMapper.insert(insertRole);
        // 重新检索插入的角色
        List<Role> role = roleMapper.selectByMap(selectMap);
        return JsonResult.ok().data("role", role.get(0));
    }

    /*
    获取角色列表
     */
    public JsonResult getRolesList() {
        // 获取角色列表
        List<GetRolesResult> rolesList = roleMapper.selectRolesList();
        // 获取页面权限
        for (GetRolesResult role : rolesList) {
            String menuIds = role.getMenuIds();
            // 权限界面list
            List<String> menus = new ArrayList<>();
            if (!StringUtils.isEmpty(menuIds)) {
                String[] menusArray = menuIds.split("/");
                List<Menu> menusList = menuMapper.selectBatchIds(Arrays.asList(menusArray));
                menus = menusList.stream().map(item -> item.getMenuName()).collect(Collectors.toList());
            }
            role.setMenus(menus);
        }
        return JsonResult.ok().data("roles", rolesList);
    }

    /*
    更新角色(给角色设置权限)
     */
    public JsonResult updateRole(RoleParam param) {
        // 乐观锁
        Role updateRole = roleMapper.selectById(param.getId());
        // 接收到前端的名称list
        List<String> menus = param.getMenus();
        // 根据名称list获得Id的list
        List<Integer> menuIdList = menus.stream().map(item -> {
            QueryWrapper<Menu> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("menu_name", item);
            Menu menu = menuMapper.selectOne(roleQueryWrapper);
            return menu.getId();
        }).collect(Collectors.toList());
        // 将Id list转成字符串
        String menuIdsStr = StringUtils.join(menuIdList, "/");
        // 根据授权人名字获取Id
        QueryWrapper<User> userQueryWrapper = new QueryWrapper();
        userQueryWrapper.eq("username", param.getAuthName());
        User user = userMapper.selectOne(userQueryWrapper);
        updateRole.setId(param.getId());
        updateRole.setMenuIds(menuIdsStr);
        updateRole.setAuthId(user.getId());
        updateRole.setAuthTime(param.getAuthTime());
        updateRole.setCreateBy(null);
        updateRole.setUpdateBy(null);
        updateRole.setCreateTime(null);
        updateRole.setUpdateBy(null);
        int i = roleMapper.updateById(updateRole);
        if (i == 0) {
            return JsonResult.error().message("该角色已被其他用户更改，请重新检索后再次尝试");
        }
        return JsonResult.ok();
    }


}
